package com.onstar.cn.map.util;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.amap.api.maps2d.AMap;
import com.amap.api.services.geocoder.GeocodeAddress;
import com.amap.api.services.geocoder.GeocodeQuery;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.GeocodeSearch.OnGeocodeSearchListener;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.onstar.cn.map.OMapActivity;
import com.onstar.cn.map.common.Constants;

public class BackgroundThread implements OnGeocodeSearchListener {

	private OMapActivity mapActivity;
	private AMap mapView;
	private String city;
	private Handler mHandler;
	private int mapLevel = -1;

	public BackgroundThread(OMapActivity mapActivity, AMap mapView,
			String city) {
		this.mapActivity = mapActivity;
		this.city = city;
		this.mapView = mapView;
		mHandler = new MessageHandler(this.mapView);
	}

	public void geoCodeCity() {
		this.geoCode();
		if (mapLevel > 0) {
			MapViewHelper.getInstance().setZoom(mapView, mapLevel);
			mapLevel = -1;
		}
	}

	/**
	 * @param mapLevel
	 *            the mapLevel to set
	 */
	public void setMapLevel(int mapLevel) {
		this.mapLevel = mapLevel;
	}

	/**
	 * @param city
	 * @throws Exception
	 */
	private void geoCode() {
		GeocodeSearch geoCoder = new GeocodeSearch(mapActivity.getApplicationContext());
		geoCoder.setOnGeocodeSearchListener(this);
		try {
			GeocodeQuery query = new GeocodeQuery(city+Constants.GOV, city);
			geoCoder.getFromLocationNameAsyn(query);
		} catch (Exception e) {
			Log.e("Error", e.getMessage(), e);
		}catch(java.lang.OutOfMemoryError e){
			Log.e("Error", e.getMessage(), e);
		}
	}

	@Override
	public void onGeocodeSearched(GeocodeResult result, int rCode) {
		if (rCode == 0) {
			if (result != null && result.getGeocodeAddressList() != null
					&& result.getGeocodeAddressList().size() > 0) {
				GeocodeAddress address = result.getGeocodeAddressList().get(0);
				mHandler.sendMessage(Message.obtain(mHandler,
						Constants.GEO_CITY_SUCCESS, address.getLatLonPoint()));
			} 
		} 
		
	}

	@Override
	public void onRegeocodeSearched(RegeocodeResult arg0, int arg1) {
		
	}
}
